//
//  ZSVideoScriptViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/10.
//

import UIKit
import ProgressHUD

class ZSVideoScriptViewController: ZSBaseViewController {
    
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var themeTextField: UITextField!
    @IBOutlet weak var communeTextField: UITextField!
    @IBOutlet weak var styleButton: UIButton!
    @IBOutlet weak var dyBtn: UIButton!
    @IBOutlet weak var dyLabel: UILabel!
    @IBOutlet weak var ksBtn: UIButton!
    @IBOutlet weak var ksLabel: UILabel!
    @IBOutlet weak var xhsBtn: UIButton!
    @IBOutlet weak var xhsLabel: UILabel!
    @IBOutlet weak var sphBtn: UIButton!
    @IBOutlet weak var sphLabel: UILabel!
    @IBOutlet weak var timeSlider: UISlider!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var timeLabelCenterX: NSLayoutConstraint!
     
    var styles: [String] = [
        "生活Vlog",
        "搞笑幽默",
        "舞蹈挑战",
        "美妆教程",
        "美食制作",
        "情景短剧",
        "旅行记录",
        "才艺展示",
        "励志演讲",
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    fileprivate func setupViews() {
        view.backgroundColor = UIColor(hexString: "#F0F3FD")
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        timeSlider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
    }
    
    @IBAction func goBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func didSelectStyle(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.styles.count == 0 { return }
        let alertController = UIAlertController(title: "请选择风格", message: "", preferredStyle: .actionSheet)
        self.styles.forEach { title in
            let action = UIAlertAction(title: title, style: .default) { (action) in
                self.styleButton.setTitle(title, for: .normal)
                self.styleButton.setTitleColor(UIColor(hexString: "#222222"), for: .normal)
            }
            alertController.addAction(action)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
        }
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }
    
    @IBAction func didSelectPlatform(_ sender: UIButton) {
        if sender.isSelected { return }
        sender.isSelected = !sender.isSelected
        if sender == dyBtn {
            dyLabel.textColor = UIColor(hexString: "533DFF")
            dyBtn.layer.cornerRadius = 10
            dyBtn.layer.borderWidth = 3
            dyBtn.layer.borderColor = UIColor(hexString: "533DFF").cgColor
            ksLabel.textColor = UIColor(hexString: "#222222")
            ksBtn.isSelected = false
            ksBtn.layer.cornerRadius = 0
            ksBtn.layer.borderWidth = 0
            ksBtn.layer.borderColor = UIColor.clear.cgColor
            xhsLabel.textColor = UIColor(hexString: "#222222")
            xhsBtn.isSelected = false
            xhsBtn.layer.cornerRadius = 0
            xhsBtn.layer.borderWidth = 0
            xhsBtn.layer.borderColor = UIColor.clear.cgColor
            sphLabel.textColor = UIColor(hexString: "#222222")
            sphBtn.isSelected = false
            sphBtn.layer.cornerRadius = 0
            sphBtn.layer.borderWidth = 0
            sphBtn.layer.borderColor = UIColor.clear.cgColor
        }else if sender == ksBtn {
            ksLabel.textColor = UIColor(hexString: "533DFF")
            ksBtn.layer.cornerRadius = 10
            ksBtn.layer.borderWidth = 3
            ksBtn.layer.borderColor = UIColor(hexString: "533DFF").cgColor
            dyLabel.textColor = UIColor(hexString: "#222222")
            dyBtn.isSelected = false
            dyBtn.layer.cornerRadius = 0
            dyBtn.layer.borderWidth = 0
            dyBtn.layer.borderColor = UIColor.clear.cgColor
            xhsLabel.textColor = UIColor(hexString: "#222222")
            xhsBtn.isSelected = false
            xhsBtn.layer.cornerRadius = 0
            xhsBtn.layer.borderWidth = 0
            xhsBtn.layer.borderColor = UIColor.clear.cgColor
            sphLabel.textColor = UIColor(hexString: "#222222")
            sphBtn.isSelected = false
            sphBtn.layer.cornerRadius = 0
            sphBtn.layer.borderWidth = 0
            sphBtn.layer.borderColor = UIColor.clear.cgColor
        }else if sender == xhsBtn {
            xhsLabel.textColor = UIColor(hexString: "533DFF")
            xhsBtn.layer.cornerRadius = 10
            xhsBtn.layer.borderWidth = 3
            xhsBtn.layer.borderColor = UIColor(hexString: "533DFF").cgColor
            ksLabel.textColor = UIColor(hexString: "#222222")
            ksBtn.isSelected = false
            ksBtn.layer.cornerRadius = 0
            ksBtn.layer.borderWidth = 0
            ksBtn.layer.borderColor = UIColor.clear.cgColor
            dyLabel.textColor = UIColor(hexString: "#222222")
            dyBtn.isSelected = false
            dyBtn.layer.cornerRadius = 0
            dyBtn.layer.borderWidth = 0
            dyBtn.layer.borderColor = UIColor.clear.cgColor
            sphLabel.textColor = UIColor(hexString: "#222222")
            sphBtn.isSelected = false
            sphBtn.layer.cornerRadius = 0
            sphBtn.layer.borderWidth = 0
            sphBtn.layer.borderColor = UIColor.clear.cgColor
        }else if sender == sphBtn {
            sphLabel.textColor = UIColor(hexString: "533DFF")
            sphBtn.layer.cornerRadius = 10
            sphBtn.layer.borderWidth = 3
            sphBtn.layer.borderColor = UIColor(hexString: "533DFF").cgColor
            ksLabel.textColor = UIColor(hexString: "#222222")
            ksBtn.isSelected = false
            ksBtn.layer.cornerRadius = 0
            ksBtn.layer.borderWidth = 0
            ksBtn.layer.borderColor = UIColor.clear.cgColor
            xhsLabel.textColor = UIColor(hexString: "#222222")
            xhsBtn.isSelected = false
            xhsBtn.layer.cornerRadius = 0
            xhsBtn.layer.borderWidth = 0
            xhsBtn.layer.borderColor = UIColor.clear.cgColor
            dyLabel.textColor = UIColor(hexString: "#222222")
            dyBtn.isSelected = false
            dyBtn.layer.cornerRadius = 0
            dyBtn.layer.borderWidth = 0
            dyBtn.layer.borderColor = UIColor.clear.cgColor
        }
    }
    
    @objc func sliderValueChanged(_ sender: UISlider) {
        let value = Int(sender.value)
        timeLabel.text = "\(value)min"
        updateValueLabelPosition()
    }
    
    func updateValueLabelPosition() {
        let thumbCenterX = timeSlider.frame.origin.x + CGFloat(timeSlider.value / timeSlider.maximumValue) * timeSlider.frame.width
        timeLabelCenterX.constant = thumbCenterX - timeSlider.frame.origin.x - timeSlider.frame.width / 2 + 5
    }
    
    @IBAction func goCreation(_ sender: UIButton) {
        guard let theme = themeTextField.text, !theme.isEmpty else {
            self.view.makeToast("请输入创作主题", position: .center)
            return
        }
        var content =  "帮我以主题【\(theme)】编写一个短视频拍摄脚本，"
        if let commune = communeTextField.text, !commune.isEmpty {
            content = content + "目标受众是【\(commune)】，"
        }
        
        if let style = styleButton.titleLabel?.text, !style.isEmpty {
            content = content + "要求如下视频风格【\(style)】，"
        }
        content = content + "时长要求在【\(Int(timeSlider.value))分钟】左右，拍摄脚本需要包含分镜时长、画面、旁白"
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbmajiabao/api/wenxinyiyan/chat"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        let parameters: [String: Any] = [
            "messages": [
                [
                    "role": "user",
                    "content": content
                ]
            ]
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                self.view.makeToast("创作失败，请重试！", duration: 1.0, position: .center)
                print("Error: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let dict = json["data"] as? [String: Any], let result = dict["result"] as? String, !result.isEmpty {
                    DispatchQueue.main.async {
                        let vc = ZSCreationResultsViewController()
                        vc.template = content
                        vc.content = result
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            } catch {
                self.view.makeToast("创作失败，请重试！", duration: 1.0, position: .center)
                print("Error parsing JSON: \(error)")
            }
        }
        task.resume()
    }
    
}
